package com.forgweb.magnet.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.forgweb.magnet.bean.BTSpreadBean;
import com.forgweb.magnet.common.BTSpreadSearch;

@Controller
@RequestMapping("/magnet")
public class MagnetController {

	Logger logger = Logger.getLogger(MagnetController.class);
	
	@RequestMapping("/{keyword}")
	@ResponseBody
	public String magnetSearch(@PathVariable("keyword")String keyword,ModelMap model){
		
		BTSpreadSearch bt = new BTSpreadSearch();
		List <BTSpreadBean> btList =bt.getBTResult(keyword);
		
		logger.info("keyword = " + keyword + ", BTlist size=" + btList.size());
		model.addAttribute("btList",btList);
		model.addAttribute("keyword",keyword);
		
		return JSON.toJSONString(model);
	}
	
	//method =RequestMethod.POST
	@RequestMapping
	public String index(@RequestParam(value="keyword",required=false)String keyword,
								ModelMap model){
		
		if(StringUtils.isEmpty(keyword)){
			return "/magnet/magnet_index";
		}
		
		model.addAttribute("keyword", keyword) ;
		
		BTSpreadSearch bt = new BTSpreadSearch();
		List <BTSpreadBean> btList =bt.getBTResult(keyword);
		
		if(btList == null || btList.size() ==0){
			model.addAttribute("msg", "未搜索到任何信息，请重新设置关键词！") ;
		}else{		
			model.addAttribute("btList", btList) ;
		}
		
		return "/magnet/magnet_index";
	}
	
	
}
